from . import news_blueprint
from flask import render_template, session, g, request, jsonify, current_app
from info.models import News, User, Comment,CommentLike
from info import constants, db
from info.utils.common import login_wrapps
from info.response_code import RET


@news_blueprint.route('/<int:news_id>')
@login_wrapps
def detail(news_id):
    # print(type(g))
    news = News.query.get_or_404(news_id)
    # 点击量+1
    news.clicks += 1
    db.session.commit()
    # 用户状态
    # user_id = session.get('user_id')
    # if user_id is None:
    #     user = None
    # else:
    #     user = User.query.get(user_id).to_login_dict()
    # 点击量排行
    from info.utils.common import get_click_list
    news_list2 = get_click_list()

    # 查询当前新闻是否被当前用户收藏
    if g.user and news in g.user.collection_news:
        is_collected = True
    else:
        is_collected = False

    # 查询当前新闻的所有评论信息
    comment_list1 = news.comments.filter_by(parent_id=None).order_by(Comment.id.desc())
    comment_list2 = [comment.to_dict() for comment in comment_list1]

    #查询当前登录的用户是否对某个评论点赞
    if g.user:
        #获取当前新闻所有评论的编号
        comment_ids=[comment.id for comment in comment_list1]
        #查询点赞表:当前新闻的评论、当前用户点赞过的数据
        likes=CommentLike.query.\
            filter_by(user_id=g.user.id).\
            filter(CommentLike.comment_id.in_(comment_ids))
        likes_ids=[like.comment_id for like in likes]
        for comment in comment_list2:
            comment['is_like']=comment.get('id') in likes_ids

    data = {
        'news': news,
        'user': g.user.to_login_dict(),
        'news_list': news_list2,
        'is_collected': is_collected,
        'comment_list': comment_list2
    }
    return render_template('news/detail.html', data=data)


@news_blueprint.route('/news_collect', methods=['POST'])
@login_wrapps
def news_collect():
    '''向用户收藏新闻的中间表中添加、删除数据'''
    # 1.接收
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 2.验证
    # 2.1非空
    if not all([news_id, action]):
        return jsonify(errno=RET.NODATA, errmsg='数据不完整')
    # 2.2登录
    if g.user is None:
        return jsonify(errno=RET.LOGINERR, errmsg='用户未登录')
    # 2.3查询新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        # 对于出现错误，需要开发人员或运维人员解决，则这种错误存入日志，如连接mysql、redis
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')
    # 2.4是否有效的news_id
    if news is None:
        return jsonify(errno=RET.DATAERR, errmsg='无效的新闻编号')
    # 2.5action的值是否有效
    if action not in ('collect', 'cancel_collect'):
        return jsonify(errno=RET.DATAERR, errmsg='无效的操作')

    # 3.处理:向中间表中添加或删除数据
    user = g.user
    if action == 'collect':
        # 收藏
        if news not in user.collection_news:
            user.collection_news.append(news)
            # db.session.add(对象)===>insert into
            # insert into ...
    else:
        # 取消收藏
        if news in user.collection_news:
            user.collection_news.remove(news)
    try:
        db.session.commit()
        # 执行insert语句
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    # 4.响应
    return jsonify(errno=RET.OK, errmsg='')


@news_blueprint.route('/comment_add', methods=['POST'])
@login_wrapps
def comment_add():
    '''
    添加评论、回复
    评论：无parent_id
    回复：有parent_id
    '''
    # 1.接收
    news_id = request.json.get('news_id')
    msg = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    # 2.验证
    # 2.1非空
    if not all([news_id, msg]):
        return jsonify(errno=RET.NODATA, errmsg='数据不完整')
    # 2.2验证新闻有效
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.err(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')
    if news is None:
        return jsonify(errno=RET.DATAERR, errmsg='新闻编号无效')
    # 2.3验证用户是否登录
    if g.user is None:
        return jsonify(errno=RET.LOGINERR, errmsg='请先登录')

    # 3.处理：创建Comemnt对象，保存到数据库
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = int(news_id)
    comment.content = msg
    # 区分是评论还是回复
    if parent_id:
        comment.parent_id = int(parent_id)
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    # 4.响应
    return jsonify(errno=RET.OK, errmsg='', data=comment.to_dict())

@news_blueprint.route('/comment_like', methods=['POST'])
@login_wrapps
def comment_like():
    #1.接收
    news_id=request.json.get('news_id')
    comment_id=request.json.get('comment_id')
    action=request.json.get('action')

    #2.验证:与收藏的逻辑类似

    #3.处理：向CommentLike表中添加或删除数据
    user_id=g.user.id
    comment = Comment.query.get(comment_id)

    if action=='add':
        #点赞
        like=CommentLike()
        like.comment_id=int(comment_id)
        like.user_id=user_id
        try:
            comment.like_count+=1

            db.session.add(like)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')
    else:
        #取消点赞
        like=CommentLike.query.filter_by(comment_id=comment_id,user_id=user_id).first()
        try:
            comment.like_count-=1

            db.session.delete(like)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库连接失败')

    #4.响应
    return jsonify(errno=RET.OK,errmsg='')
